package com.ybkj.daijia.server.event.listener;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.event.model.MemberConsumedEvent;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.GasOrderService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import java.math.BigDecimal;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Component
public class MemberConsumedEventListener implements ApplicationListener<MemberConsumedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(MemberConsumedEventListener.class);


    @Autowired
    private SmsService smsService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private FreightService freightService;

    @Autowired

    private ZhuanxianService zhuanxianService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private GasOrderService gasOrderService;


    @Override
    @Async
    public void onApplicationEvent(MemberConsumedEvent event) {

        logger.debug("member ConsumedEvent event:{}", "");

        PassengerAccount passengerAccount = (PassengerAccount) event.getSource();
        String phone = event.getPhone();

        Long orderCompanyId = null;

        if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_DAIJIA)) {
            Order order = orderService.findOne(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        } else if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_ZHUANCHE)) {
            com.ybkj.daijia.server.zhuan.Order order = zhuancheService
                .findOne(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        } else if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_PAOTUI)) {
            com.ybkj.daijia.server.errand.Order order = errandService
                .findOne(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        } else if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_FREIGHT)) {
            com.ybkj.daijia.server.freight.Order order = freightService
                .findOne(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        } else if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_ZHUANXIAN)) {
            com.ybkj.daijia.server.zhuanxian.Order order = zhuanxianService
                .findOne(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        } else if (passengerAccount.getOrderType().equals(PassengerAccount.ORDER_TYPE_GASSTATION)) {
            com.ybkj.daijia.server.gasstation.Order order = gasOrderService
                .queryById(passengerAccount.getOrderId());
            orderCompanyId = order.getCompanyId();
        }

        BigDecimal money = new BigDecimal(passengerAccount.getMoney());
        Setting setting = settingUtils.get();
        Company orderCompany = companyService.findOne(orderCompanyId);
        Company maincompany = companyService.getMain();
        if (setting.isSmsMainCompany()) {
            orderCompany = maincompany;
        }

        if (StringUtils.isNotBlank(phone)) {
            Long enterpriseId = passengerAccount.getEnterprise_id();
            Enterprise enterprise = memberService.findOneEnterprise(enterpriseId);
            SmsTemplet templet = smsService
                .findByAlias(orderCompany.getId(), SmsType.memberConsumedRecord);
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                try {
                    //smsService.sendSms(phone, "memberConsumedRecord", "{\"支出金额\":\""+money.setScale(2, BigDecimal.ROUND_HALF_UP).toString()+"\",\"余额\":\""+enterprise.getDrawMoney().add(enterprise.getNodrawMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()+"\",\"电话\":\""+maincompany.getTelephone()+"\"}", orderCompany.getId(), 0, orderCompany.getSignName());
                    //短信发送（改）
                    JSONObject smsParam = new JSONObject();
                    smsParam.put("money", money.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    smsParam.put("balance",
                        enterprise.getDrawMoney().add(enterprise.getNodrawMoney())
                            .setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    smsParam.put("tel", maincompany.getTelephone());
                    smsService.sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                        orderCompany.getId(), 0, orderCompany.getSignName());
                } catch (Exception e) {
                    logger.error("发送短信发生异常：{}", e.getMessage());
                }
            }
        } else {
            Long passengerId = passengerAccount.getPassenger_id();
            Passenger passenger = memberService.findOnePassenger(passengerId);

            //发送短信
            if (null != passenger) {
                SmsTemplet templet = smsService
                    .findByAlias(orderCompany.getId(), SmsType.memberConsumedRecord);
                if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                    try {
                        //smsService.sendSms(passenger.getPhone(), "memberConsumedRecord", "{\"支出金额\":\""+money.setScale(2, BigDecimal.ROUND_HALF_UP).toString()+"\",\"余额\":\""+passenger.getDrawMoney().add(passenger.getNodrawMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString()+"\",\"电话\":\""+maincompany.getTelephone()+"\"}", orderCompany.getId(), 0, orderCompany.getSignName());
                        //短信发送（改）
                        JSONObject smsParam = new JSONObject();
                        smsParam
                            .put("money", money.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        smsParam.put("balance",
                            passenger.getDrawMoney().add(passenger.getNodrawMoney())
                                .setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        smsParam.put("tel", maincompany.getTelephone());
                        smsService.sendSms(passenger.getPhone(), templet.getTemplateId(),
                            smsParam.toJSONString(), orderCompany.getId(), 0,
                            orderCompany.getSignName());

                    } catch (Exception e) {
                        logger.error("发送短信发生异常：{}", e.getMessage());
                    }
                }
            }
        }

    }

}
